package com.zero.manager_following.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zero.manager_following.common.Result;
import com.zero.manager_following.entity.User;
import com.zero.manager_following.exception.ServiceException;
import com.zero.manager_following.interceptor.AuthAccess;
import com.zero.manager_following.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.BatchUpdateException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能：提供接口返回数据
 * 作者：zero
 * 日期：2024/9/13 12:25
 */
@CrossOrigin
@RestController
@RequestMapping("/user") //定义一级路径
public class WebController {

    @Resource
    private UserService userService;

    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        try {
            userService.save(user);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("该用户名已存在，请更换其他用户名");
            }else{
                return Result.error("添加失败");
            }
        }
        return Result.success("添加成功");
    }

//    @AuthAccess
    @GetMapping("/list")
    public Result list() {
        //select * from user order by id desc
        return Result.success(userService.list(new QueryWrapper<User>().orderByDesc("id")));
    }

    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam String username, @RequestParam String name, @RequestParam Integer pageNum,
                          @RequestParam Integer pageSize) {
//        Page<User> page = new Page<>(userService.getTotal(username, name), userService.byPage(username, name, pageNum, pageSize));
//        return Result.success(page);
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().orderByDesc("id");
        queryWrapper.like(StrUtil.isNotBlank(username), "username", username);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        IPage<User> page = new Page<>(pageNum, pageSize);
        userService.page(page, queryWrapper);
        return Result.success(page);
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateById(user);
        return Result.success("修改成功");
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
//        Integer curId = TokenUtils.getCurrentUser().getId();
//        if (id.equals(curId)) {
//            throw new RuntimeException("不能删除当前用户");
//        }
        userService.removeById(id);
        return Result.success("删除成功");
    }

    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids){
//        if(ids.contains(TokenUtils.getCurrentUser().getId())){
//            throw new RuntimeException("不能删除当前用户");
//        }
        userService.removeBatchByIds(ids);
        return Result.success();
    }

    @GetMapping("selById/{id}")
    public Result selectById(@PathVariable Integer id){
        return Result.success(userService.getById(id));
    }


    @PostMapping("/login")
    public Result login(@RequestBody User user){
        String username = user.getUsername();
        String password = user.getPassword();
        //hutools 校验
        if(StrUtil.isBlank(username)|| StrUtil.isBlank(password)){
            Result.error("用户名不能为空");
        }
        user = userService.login(username,password);
        return Result.success(user);
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        if(StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())){
            return Result.error("用户名或密码为空");
        }
        userService.register(user);
        return Result.success(user);
    }

    @AuthAccess
    @PutMapping("/resetPwd")
    public Result resetPwd(@RequestBody User user){
        userService.updatePwd(user);
        return Result.success("修改成功");
    }

    /**
     * 批量导出数据
     */
    @GetMapping("/export")
    public void exportData(@RequestParam(required = false) String username,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) String ids,
                           HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<User> list = null;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //输入条件的过滤
        queryWrapper.like(StrUtil.isNotBlank(username), "username", username);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        //选择数据的过滤
        if(StrUtil.isNotBlank(ids)){
            List<Integer> collectIds =
                    Arrays.stream(ids.split(",")).map(Integer::parseInt).toList();
            queryWrapper.in("id",collectIds);
        }

        //查询出当前User表的所有数据
        list = userService.list(queryWrapper);

        writer.write(list,true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String filename = URLEncoder.encode("用户信息", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream,true);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 批量导入
     * @param file 传入的excel对象
     * @return 批量导入成功条数
     */
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<User> users = reader.readAll(User.class);
        //写入到数据库中
        try {
            for (User user : users) {
                userService.saveByNoId(user);
            }
        } catch (Exception e) {
            throw new ServiceException("出现重复的数据，批量添加失败");
        }
        return Result.success();
    }
}
